const loginApi = require('../../services/loginApi');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasGetUserProfile: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const hasGetUserProfile = wx.getUserProfile? true : false;
    this.setData({ hasGetUserProfile })
  },

  /**
   * 登录注册流程
   */
  onWxLogin: async function() {
    const { getUserInfo, getLoginCertificate } = this;
    Promise.all([getUserInfo(), getLoginCertificate()])
    .then((res) => {
      console.debug("[debug code]: ", res[1]);
      console.debug("[debug userinfo]: ", res[0]);

      return {
        code: res[1],
        encryptedData: res[0].encryptedData,
        iv: res[0].iv
      };
    })
    .then(async (res) => {
      const { code, encryptedData, iv } = res;
      await loginApi.login(code, encryptedData, iv);
    })
    .catch((err) => {
      console.debug(err.errMsg);
    });
  },

  /**
   * 授权用户信息
   */
  getUserInfo: function () {
    return new Promise((resolve, reject) => {
      const wx_getUserInfo = wx.getUserProfile? 
            wx.getUserProfile : wx.getUserInfo;
      wx_getUserInfo({
        desc: "完善会员资料",
        success: (result) => resolve(result),
        fail: (error)=> reject(error)
      });
    });
  },

  /**
   * 获取用户登录凭证 Code
   */
  getLoginCertificate: function () {
    return new Promise((resolve, reject) => {
       wx.login({
        success: (res) => resolve(res.code),
        fail: (error) => reject(error)
      });
    });
  },
})